<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\manage\controller\admin;

use buwang\base\AdminBaseController;
use buwang\service\MiniappService;
use buwang\traits\CrudControllerTrait;
use think\facade\Db;
use think\facade\View;

class Miniapp extends AdminBaseController
{
    use CrudControllerTrait;

    protected $model = null;//模型实例

    protected function initialize()
    {
        parent::initialize();

        $this->model = new \app\common\model\Miniapp();
    }

    /**
     * 查看
     */
    public function index()
    {
        if (request()->isAjax()) {
            //已安装应用列表
            $list = $this->model->order('id asc')->select();

            //所有应用列表 除去系统目录
            //系统目录
            $system_dir = ['api', 'common', 'home', 'manage'];
            $dirs = array_diff(array_map('basename', glob(root_path() . 'app/' . '*', GLOB_ONLYDIR)), $system_dir);

            // 已安装应用的目录列表
            $apps = $this->model->order('id asc')->column('*', 'dir');
            //遍历插件列表
            foreach ($dirs as $name) {
                //是否已经安装过
                if (!isset($apps[$name])) {
                    $version = MiniappService::getVersion($name);

                    if (!$version) continue;

                    $version['dir'] = $name;
                    $version['template_id'] = 0;
                    $version['sell_price'] = 0;
                    $version['market_price'] = 0;
                    $version['expire_day'] = 0;
                    $version['logo_image'] = '';
                    $version['qrcode_image'] = '';
                    $version['style_images'] = '';
                    $version['status'] = -1;
                    $version['sort'] = 0;
                    $version['create_time'] = 0;
                    $version['update_time'] = 0;

                    $list[] = $version;
                }
            }

            $data = compact('list');
            return $this->success('successful', $data);
        }

        return view();
    }

    /**
     * 安装应用
     * @param string $dir
     */
    public function install($dir = '')
    {
        if (request()->isPost()) {
            $dir = $dir ? $dir : request()->post("dir/s");
            if (!$dir) return $this->error('应用名有误');

            Db::startTrans();
            try {
                MiniappService::install($dir);

                Db::commit();
            } catch (\Throwable $e) {
                Db::rollback();
//                return $this->error($e->getMessage() . ' - ' . $e->getFile() . ' - ' . $e->getLine());
                return $this->error($e->getMessage());
            }
            return $this->success();
        }
    }

    /**
     * 卸载应用
     * @param string $dir
     */
    public function uninstall($dir = '')
    {
        if (request()->isPost()) {
            if (!$dir) return $this->error('应用名不能为空');

            $this->model->startTrans();
            try {
                MiniappService::uninstall($dir);

                $this->model->commit();
            } catch (\Throwable $e) {
                $this->model->rollback();
                return $this->error($e->getMessage());
            }
            return $this->success();
        }
    }

    /**
     * 编辑
     * @menu true
     * @param int $id
     */
    public function edit($id = 0)
    {
        $row = $this->model->find($id);

        if (request()->isPost()) {
            if (!$row) return $this->error('记录不存在');

            $param = request()->post();
            //TODO 参数验证

            $this->model->startTrans();
            try {
                //TODO 更新记录
                $row->save($param);
                $this->model->commit();
            } catch (\Exception $e) {
                $this->model->rollback();
                return $this->error('编辑失败', ['errorMsg' => $e->getMessage()]);
            }
            return $this->success('编辑成功');
        }

        if (!$row) return $this->error_jump('记录不存在');

        View::assign('row', $row);

        //查询租户
        $members = \app\common\model\Member::field('id as value, nickname as title')->select();
        View::assign('members', json_encode($members));

        return view();
    }
}
